package com.peng.leetcode.tree;

/**
 * Flatten2
 * <p>
 * 114. 二叉树展开为链表
 * https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/
 * 给你二叉树的根结点 root ，请你将它展开为一个单链表：
 * <p>
 * 展开后的单链表应该同样使用 TreeNode ，其中 right 子指针指向链表中下一个结点，而左子指针始终为 null 。
 * 展开后的单链表应该与二叉树 先序遍历 顺序相同。
 *
 * <p>
 * Created on 2022/11/21
 *
 * @author lupeng
 */
public class Flatten2 {

    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        TreeNode curr = root;
        while (curr != null) {
            if (curr.left != null) {
                TreeNode rightNode = findRightNode(curr.left);
                rightNode.right = curr.right;
                curr.right = curr.left;
                curr.left = null;
            }
            curr = curr.right;
        }
    }

    private TreeNode findRightNode(TreeNode n) {
        TreeNode res = n;
        while (res.right != null) {
            res = res.right;
        }
        return res;
    }
}
